package org.elec.mac.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.elec.mac.entity.*;
import org.elec.mac.page.PageList;
import org.elec.mac.page.PageProperty;
import org.elec.mac.service.*;
import org.elec.mac.utils.JSONUtil;
import org.elec.mac.utils.Maxcup;
import org.elec.mac.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 配方
 * Created by Bean on 2018/3/27.
 */
@Slf4j
@Controller
public class FormulaController extends BaseController {

    @Autowired
    private SFormulaService sFormulaService;

    @Autowired
    private SMaterialService sMaterialService;

    @Autowired
    private SProductService sProductService;

    @Autowired
    private SMachineMenuService sMachineMenuService;

    @Autowired
    private SMachineMaterialService sMachineMaterialService;

    @RequestMapping("/formula_list.do")
    public String formulaListHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                     @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                     @RequestParam(value = "limit", required = false) String limit,
                                     @RequestParam(value = "page", required = false) String page) throws IOException {
        Integer productid = Utils.parseInt(this.getParameter(request, "productid"), 0);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("id",  productid);
        //获取产品信息
        SProduct sProduct = sProductService.get(param);
        model.put("sProduct", sProduct);
        param.clear();
        param.put("pid", productid);
        param.put("sign", 0);
        //获取该产品的配方
        List<Map<String, Object>> list = sFormulaService.getFormulaInfoList(param);
        model.put("formulaList", list);
        param.put("sign", 1);
        List<Map<String, Object>> lists = sFormulaService.getFormulaInfoList(param);
        model.put("formulbList", lists);
        //获取不在产品配方里面的原料
        List<SMaterial> materialList = sMaterialService.getProductMaterialInfo(productid);
        model.put("materialList", materialList);
        model.put("productid", productid);
        return "/formula/formula_list";
    }

    //新增配方
    @RequestMapping(value = "/formula_add.do")
    public void formulaAddHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                     @RequestParam(value = "action", required = false, defaultValue = "") String action) throws IOException {
        String pid = this.getParameter(request, "productid");
        Map<String, Object> param = new HashMap<>();
        param.put("pid", pid);
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("do".equals(action)) {
            try {

                Long productid =  Utils.parseLong(this.getParameter(request, "productid"),0);
                Long meterialid = Utils.parseLong(this.getParameter(request, "meterialid"),0);
                Integer amount = Utils.parseInt(this.getParameter(request, "amount"),0);
                List<SMachineMenu> sMachineMenuList = sMachineMenuService.list(param);

                if(meterialid == 0) {
                    result.setSuccess(false);
                    result.setMsg("配方不能为空");
                }
                if(amount == 0) {
                    result.setSuccess(false);
                    result.setMsg("数量不能为空");
                }
                if(sMachineMenuList != null && sMachineMenuList.size() > 0) {
                    result.setSuccess(false);
                    result.setMsg("该产品已经存在机台，不能新增配方");
                }
                if(result.isSuccess()) {
                    SFormula formula = new SFormula();
                    formula.setName("");
                    formula.setPid(productid);
                    formula.setMaid(meterialid);
                    formula.setAmount(amount);
                    sFormulaService.insert(formula);
                    log.info("配方新增");
                }
            } catch(Exception ex) {
                log.error("配方新增错误", ex);
                result.setSuccess(false);
                result.setMsg("配方新增错误");
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }
    //修改配方
    @RequestMapping(value = "/formula_edit.do")
    public void formulaEditHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                      @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                      @RequestParam(value = "id", required = false, defaultValue = "") String id)
            throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("edit".equals(action)) {
            try {
                Map<String, Object> params = new HashMap<>();
                params.put("id", Utils.parseLong(id, 0L));
                SFormula sFormula = sFormulaService.get(params);
                params.clear();
                params.put("id",  sFormula.getMaid());
                result.getBody().put("sFormula", sFormula);
                SMaterial sMaterial = sMaterialService.get(params);
                result.getBody().put("sMaterial", sMaterial);
                log.info("配方参数修改开启");
            } catch(Exception ex) {
                log.error("配方参数修改开启错误", ex);
                result.setSuccess(false);
                result.setMsg("配方参数修改开启错误");
            }
        }
        if("doEdit".equals(action)) {
            Long pid = Utils.parseLong(this.getParameter(request,"pid"),0);
            try {
                Integer amount = Utils.parseInt(this.getParameter(request, "amount"), 0);
                if(amount == 0) {
                    result.setSuccess(false);
                    result.setMsg("数量不能为空");
                }
                if(result.isSuccess()) {
                    SFormula formula = new SFormula();
                    formula.setId(Utils.parseLong(id, 0L));
                    formula.setAmount(amount);
                    sFormulaService.update(formula);
                    log.info("配方修改");

                    //更新机台库存
                    Map<String, Object> param = new HashMap<>();
                    param.put("pid", pid);
                    List<SFormula> sFormulaList = sFormulaService.list(param);
                    List<SMachineMenu> menuList = sMachineMenuService.list(param);
                    if(sFormulaList != null && sFormulaList.size() > 0
                            && menuList != null && menuList.size() > 0) {
                        for (SMachineMenu item : menuList) {
                            param.clear();
                            param.put("machid", item.getMachid());
                            List<SMachineMaterial> sMachineMaterialList = sMachineMaterialService.list(param);
                            item.setMaxcup(Maxcup.result(sFormulaList, sMachineMaterialList));
                            sMachineMenuService.update(item);
                        }
                    }
                }
            } catch(Exception ex) {
                log.error("配方修改错误", ex);
                result.setSuccess(false);
                result.setMsg("配方修改错误");
            }
        }
        if("doDelete".equals(action)) {
           try {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("id",id);
                sFormulaService.delete(params);
                log.info("配方删除");
            } catch(Exception ex) {
                log.error("配方删除错误", ex);
                result.setSuccess(false);
                result.setMsg("配方删除错误");
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }
}
